// 关联页面搜索
import React, { useCallback, useState } from 'react';
import { Image, Text, View } from '@tarojs/components';
import TitleBar from '@/src/components/titleBar';
import './index.less';
import { AtSearchBar } from 'taro-ui';
import { observer } from 'mobx-react-lite';
import {
  searchCabinetListFun,
  searchListFun,
} from '@/src/common/method/wikiFun';
import store from '@/src/store';
import Taro from '@tarojs/taro';

const RelateSearch: React.FC = () => {
  const [value, setValue] = useState('');
  // 雪茄和雪茄柜搜索结果
  const [productionList, setProductionList] = useState<any[]>([]);
  // 空白页面显示标志
  const [showEmpty, setShowEmpty] = useState<boolean>(false);
  // 雪茄柜的数据
  const [cabinetList, setCabinetList] = useState<any[]>([]);

  // 清除输入内容
  const handleClear = useCallback(() => {
    setValue('');
  }, []);

  // 处理输入（保持与原逻辑一致：每次输入即发起两次搜索）
  const onChange = useCallback((val: string) => {
    setValue(val);

    const cabinetParams = {
      name: val,
      pageNo: 1,
      pageSize: 20,
    };
    searchCabinetListFun(cabinetParams)
      .then((res: any) => {
        if (res.list && res.list.length > 0) {
          setShowEmpty(false);
          setCabinetList(res.list);
        } else {
          setShowEmpty(true);
          setCabinetList([]);
        }
      })
      .catch(() => {});

    const productParams = {
      productKeyWord: val,
      pageNo: 0,
      pageSize: 20,
    };
    searchListFun(productParams)
      .then((res: any) => {
        console.log(res, 'relateres==');
        if (res.list && res.list.length > 0) {
          setShowEmpty(false);
          setProductionList(res.list);
        } else {
          setShowEmpty(true);
          setProductionList([]);
        }
      })
      .catch((err: any) => {
        console.log(err, 'err==');
      });
  }, []);

  // 关联（雪茄）
  const relatedToPublish = useCallback((item: any) => {
    const data = {
      cigarSku: item.sku,
      contentCigarBrand: item.brandName,
      contentCigarZh: item.productName,
      contentCigarImg: item.productImg,
    };
    store.publishStore.setContentCigar(data);
    setTimeout(() => {
      Taro.navigateBack();
    }, 300);
  }, []);

  // 关联（雪茄柜）
  const relatedCabinetToPublish = useCallback((item: any) => {
    const data = {
      model: item.model,
      contentCigarCabinetBrand: item.cigarCabinetBrand,
      contentCigarCabinetZh: item.cigarCabinetZh,
      contentCigarCabinetImg: item.cigarCabinetImg,
    };
    store.publishStore.setContentCigarCabinet(data);
    setTimeout(() => {
      Taro.navigateBack();
    }, 300);
  }, []);

  return (
    <View
      className="search"
      style={{ paddingTop: `${store.commonStore.pageAreaTop}rpx` }}
    >
      <TitleBar showLeftBack={true} title="搜索" />
      <View className="search-body">
        <View className="relate-search-box">
          <AtSearchBar
            placeholder="搜索关联雪茄或雪茄柜"
            className="relate-search-bar"
            actionName="取消"
            value={value}
            showActionButton
            onChange={onChange}
            onActionClick={handleClear}
          />
        </View>

        {cabinetList.length > 0 &&
          cabinetList.map((item: any, index: number) => {
            const key =
              item.id ?? item.model ?? item.cigarCabinetZh ?? `cab-${index}`;
            return (
              <View className="cigar-item-content" key={key}>
                <View>
                  <Image src={item.cigarCabinetImg} />
                </View>
                <View>
                  <View className="cigar-item-brand">
                    {item.cigarCabinetZh}（{item.cigarCabinetBrand}）
                  </View>
                  <View className="cigar-item-model">{item.model}</View>
                  {/* <View className="cigar-item-color">黑色</View> */}
                </View>
                <View
                  className="related"
                  onClick={() => relatedCabinetToPublish(item)}
                >
                  关联
                </View>
              </View>
            );
          })}

        {productionList.length > 0 &&
          productionList.map((item: any, index: number) => {
            const key =
              item.id ??
              item.sku ??
              `${item.productName}-${item.brandName}-${index}`;
            return (
              <View key={key}>
                <View className="xuejia-body">
                  <View className="tittle-main">
                    {item.brandName}
                  </View>
                  <View className="tittle-sub">
                    {item.productName}
                  </View>
                  <Image className="xuejia-icon" src={item.productImg} />
                  <View
                    className="xuejia-relate"
                    onClick={() => relatedToPublish(item)}
                  >
                    关联
                  </View>
                </View>
              </View>
            );
          })}

        {productionList.length === 0 &&
          cabinetList.length === 0 &&
          showEmpty && (
            <View className="search-none">
              <View className="search-none-content">
                <Image
                  className="search-none-icon"
                  src="https://file.linkcook.cn/image/wineMiniProgram/search/searchNone.png"
                />
                <Text className="search-none-text">抱歉，搜索无结果</Text>
              </View>
            </View>
          )}
      </View>
    </View>
  );
};

export default observer(RelateSearch);
